package com.tk.exam.utils;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author: xujg
 * @Description: TODO
 * @date: 2018-06-09 10:42
 */
public class CreateFileUtil {
    /**
     * 生成.json格式文件
     */
    public static boolean createJsonFile(String jsonString, String filePath, String fileName){
        // 标记文件生成是否成功
        boolean flag = true;

        // 拼接文件完整路径
        String fullPath = filePath + File.separator + fileName + ".json";

        // 生成json格式文件
        try {
            // 保证创建一个新文件
            File file = new File(fullPath);
            if (!file.getParentFile().exists()) { // 如果父目录不存在，创建父目录
                file.getParentFile().mkdirs();
            }
            if (file.exists()) { // 如果已存在,删除旧文件
                file.delete();
            }
            file.createNewFile();

            // 格式化json字符串
            jsonString = JsonFormatTool.formatJson(jsonString);

            // 将格式化后的字符串写入文件
            Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            write.write(jsonString);
            write.flush();
            write.close();
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }

        // 返回是否成功的标记
        return flag;
    }
    /**
     * 下载文件
     * @param
     * @return javax.servlet.http.HttpServletResponse
     */
    public static HttpServletResponse download(String path, HttpServletResponse response,String agent) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();


            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + encodeDownloadFilename(filename,agent));
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }


    /**
     * 下载本项目路径下的文件
     * @param
     * @return javax.servlet.http.HttpServletResponse
     */
    public static HttpServletResponse downloadLocal(String fileName, HttpServletResponse response,String agent) {
        try {
            //设置文件路径
            ClassPathResource resource = new ClassPathResource(fileName);
            InputStream fis = resource.getInputStream();
//            Resource resource = new ClassPathResource(fileName);
//            File file = resource.getFile();
            // 取得文件名。
//            String filename = file.getName();
            // 取得文件的后缀名。
//            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();


            // 以流的形式下载文件。
//            InputStream fis = new BufferedInputStream(new FileInputStream(file));

//
//            byte[] buffer = new byte[fis.available()];
//            fis.read(buffer);
//            fis.close();
            // 清空response
//            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + encodeDownloadFilename(fileName,agent));
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            OutputStream out = new BufferedOutputStream(response.getOutputStream());

            //开始copy
            int bufferSize = 65000;
            byte [] b = new byte[bufferSize];
            int k = 0;
            int len = 0;
            while ((len = fis.read (b, 0, bufferSize)) > -1){
                out.write (b, 0, len);
                k += len;
            }
            out.flush ();
            out.close ();
            fis.close ();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }



    /**
     * 不创建文件，直接下载到前台
     * @param response, agent, fileName, jsonString
     * @return javax.servlet.http.HttpServletResponse
     */
    public static HttpServletResponse downLoadFile(HttpServletResponse response, String agent, String fileName, String jsonString){
        try {
            // 格式化json字符串
            jsonString = JsonFormatTool.formatJson(jsonString);
            //反转移
            String jsonStr = releaseSpecialWords(jsonString);
            //获取文件内容的字节数
            byte[] bytes = jsonStr.getBytes("utf-8");
            //读取文件内容
            ByteArrayInputStream in = new ByteArrayInputStream (bytes);
            //设置下载响应头
            response.setContentType ("application/json; charset=utf-8");
            response.setContentLength ((int) bytes.length);
            response.setHeader ("Content-Disposition", "attachment;filename=" + encodeDownloadFilename(fileName,agent));
            response.setCharacterEncoding ("utf-8");
            ServletOutputStream out = response.getOutputStream ();

            //开始copy
            int bufferSize = 65000;
            byte [] b = new byte[bufferSize];
            int k = 0;
            int len = 0;
            while ((len = in.read (b, 0, bufferSize)) > -1){
                out.write (b, 0, len);
                k += len;
            }
            out.flush ();
            out.close ();
            in.close ();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    private static String releaseSpecialWords(String jsonString) {
        if(!StringUtils.isEmpty(jsonString)){
            if(jsonString.contains("//}")){
                jsonString= jsonString.replaceAll("//}","}");
            }
            if(jsonString.contains("//]")){
                jsonString= jsonString.replace("//]","]");
            }
            if(jsonString.contains("//,")){
                jsonString= jsonString.replace("//,",",");
            }
            if(jsonString.contains("//{")){
                jsonString= jsonString.replace("//{","{");
            }
            if(jsonString.contains("//[")){
                jsonString= jsonString.replace("//[","[");
            }
        }
        return jsonString;

    }

    /**
     * 下载文件时，针对不同浏览器，进行附件名的编码
     *
     * @param filename
     *            下载文件名
     * @param agent
     *            客户端浏览器
     * @return 编码后的下载附件名
     * @throws IOException
     */
    public static String encodeDownloadFilename(String filename, String agent)
            throws IOException {
        if (agent.contains("firefox")) { // 火狐浏览器
            filename = "=?UTF-8?B?"
                    + new BASE64Encoder().encode(filename.getBytes("utf-8"))
                    + "?=";
            filename = filename.replaceAll("\r\n", "");
        } else { // IE及其他浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+"," ");
        }
        return filename;
    }


}